<template>
  <base-layout
    :dialog-title='dialogTitle'
    :dialog-visible='dialogVisible'
    @dialog-close='dialogClose'
    :dialogWidth='dialogWidth'
  >
    <template #searchPanel>
      <el-row>
        <el-col :span='12'>申请基本信息</el-col>
        <el-divider content-position='center'></el-divider>
      </el-row>
      <form-create
        v-model='cusutomerFormModel'
        :rule='rule'
        @storage-change='getWareHouse'
        @storage-site-change='getStorageSite'
        :option='option'
      />
    </template>

    <template #contentPanel>
      <el-row>
        <el-col :span='12'>车型列表</el-col>
        <el-col :span='12' class='text-right'>
          <el-button type='primary' @click='addCar'
          ><i class='el-icon-plus'></i> 添加车型
          </el-button
          >
        </el-col>
      </el-row>
      <el-divider content-position='center'></el-divider>

      <data-table
        :value='carList'
        :has-action='true'
        :table-column-attributes='tableColumnAttributes'
        :width='160'
        :isShowPage='false'
      >
        <template #action='{ row }'>
          <i
            class='el-icon-delete'
            title='删除'

            style='color: red; margin-left: 15px; cursor: pointer'
            @click='handleDataDelete(row)'
          ></i>
        </template>
      </data-table>

      <el-row>
        <el-col :span='12'>
          移库总量：<strong>{{ carList.length || 0 }}</strong>
        </el-col>
        <el-col :span='12' class='text-right'>
          <el-button type='success' @click='saveUpdate'>保存</el-button>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <NumberCarModel @getList='getList' :store-id='storeId' />
    </template>
  </base-layout>
</template>

<script>
import {
  addData,
  updateData,
  findById,
  getInven
} from '@/api/pre-sale/newCarStock/moveStorageApply'
import baseMixin from '@/mixins/base'
import { rulesForm } from './rules'
import { mapGetters } from 'vuex'
import { transferLabelAndValue } from '@/utils/pre-sale'
import { findByStore } from '@/api/after-sale/storehouseManage/warehouseManage'
import { storageSite } from '@/api/pre-sale/boutiqueStock/inventoryCheck'
import NumberCarModel from '@/components/SelectCarModel/numberCarModel'

export default {
  props: ['id'],
  components: { NumberCarModel },
  name: '',

  mixins: [baseMixin({})],
  data() {
    return {
      dialogTitle: '车型选中',
      cusutomerFormModel: {},
      rule: rulesForm,
      option: {
        // 显示表单重置按钮
        resetBtn: false,
        submitBtn: false
      },

      pageSize: 5,
      totalCount: 0,
      dialogWidth: '1200px',
      disabledType: false,
      carList: [],
      tableDataMapObj:[],
      storeId: '',
      tableColumnAttributes: [
        { name: '仓库/仓位', value: 'storage', type: 'text' },
        { name: '车架号', value: 'vin', type: 'text' },
        { name: '品牌', value: 'brandName', type: 'text' },
        { name: '车系', value: 'seriesName', type: 'text' },
        { name: '车型', value: 'modelName', type: 'text' },
        // { name: '车身色/内饰色/车顶色', value: 'genderCst', type: 'text' },
         {
          name: '车身色',
          value: 'outColor',
          type: 'input',
        },
         {
          name: '内饰色',
          value: 'inColor',
          type: 'input',
        },
         {
          name: '车顶色',
          value: 'roofColor',
          type: 'input',
        },
        { name: '增配件及价格明细', value: 'addPartsDetail', type: 'inputNumber' },
        { name: '前装及价格明细', value: 'qzDetail', type: 'inputNumber' },
        { name: '二网展车押金(元)', value: 'zcyj', type: 'inputNumber' },
        { name: '备注', value: 'remark', type: 'text' }
      ]
    }
  },
  computed: {
    ...mapGetters(['stores'])
  },
  async created() {
  },

  methods: {
    async getInven() {
      await getInven(this.$route.query.id).then(res => {
        const { success, data } = res
        if (success) {
          this.getWareHouse(data.storeId)
          this.cusutomerFormModel.setValue(res.data)
          this.$nextTick(() => {
            this.getStorageSite(data.storageId)
          })
        }
      })
    },
    format(res) {
      return res.map((data) => {
        if (!data.storage) {
          data.storageNames = `${data.storageName}/${data.storageSiteName}`
        }
        data.inventoryId=data.id;
        delete data['id'];
        return data
      })
    },
    // 获取仓库
    async getWareHouse(id) {
      this.storeId = id
      const { data } = await findByStore(id)
      this.cusutomerFormModel.updateRule('storageId', {
        options: transferLabelAndValue(data, ['storageName', 'id'])
      })
    },
    // 获取仓位
    async getStorageSite(value) {
      if (value) {
        const param = {
          storageId: value,
          storeId: this.cusutomerFormModel.getValue('storeId')
        }
        const { data } = await storageSite(param)
        this.storageSitList = data.content || []
        this.cusutomerFormModel.updateRule('storageSiteId', {
          options: transferLabelAndValue(data.content, ['storageSiteName', 'id'])
        })
      } else {
        this.cusutomerFormModel.updateRule('storageSiteId', {
          options: []
        }, true)
        this.cusutomerFormModel.setValue({ storageSiteId: '' }, true)
      }
    },
    addCar() {
      this.dialogVisible = true
    },
     tableDataMap() {
      let listIds = []
      this.carList.map((item) => {
        listIds=[...listIds,item.id]
      })
      this.tableDataMapObj = [...new Set(listIds)]
    },
    getList(selection) {
      let tableList = []
      selection.forEach((item) => {
        if (!this.tableDataMapObj.includes(item.id)) {
          tableList.push(item)
        }
      })
      let d= this.format(tableList)
      this.carList.push(...d)
      
      this.tableDataMap()
     
      this.dialogClose()
    },
    async saveUpdate() {
      this.cusutomerFormModel.submit(async(formData) => {
        const params = {
          ...formData,
          carList: this.carList
        }
        if (this.id) {
          await updateData({ ...params, id: this.id })
        } else {
          await addData({...params,reviewStatus:null})
        }
        this.$router.push({ name: 'moveStorageApply' })
      })
    },

    editCarInfo(row, type) {
      this.currentCar = row
      this.type = type
      this.dialogVisible = true
    },
    handleDataDelete(index) {
      this.carList.splice(index, 1)
    }
  },
  async mounted() {
    setTimeout(() => {
      this.cusutomerFormModel.updateRule('storeId', {
        options: transferLabelAndValue(this.stores, ['storeName', 'id'])
      })
    }, 500)

    if (this.id) {
      const { data } = await findById(this.id)
      this.getWareHouse(data.storeId)
      this.cusutomerFormModel.setValue(data)
      this.$nextTick(() => {
        this.getStorageSite(data.storageId)
        this.carList = this.format(data.carList)
      })
    } else if (this.$route.query.id) {
      this.getInven()
    }
  }
}
</script>

<style lang='scss' scoped>
.mt10 {
  margin-top: 10px;
}

.ml10 {
  margin-left: 10px;
}
</style>
